﻿/*
 * Copyright 2005-2011 Edward L. Stauff.                  Contact: <EdStauff@gmail.com>.
 * 
 * This file, "XmlError.cs", is part of the "Stauffware.Xml" library.
 * "Stauffware.Xml" is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser Public License as published by the 
 * Free Software Foundation, either version 3 of the License, or (at your 
 * option) any later version.
 * 
 * "Stauffware.Xml" is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU Lesser Public License along  
 * with "Stauffware.Xml".  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.Text;
using Stauffware.Common.Core;

namespace Stauffware.Common.Xml
{
	/// <summary>
	/// An error that occurred while reading an XML file.
	/// </summary>
	public class XmlError : Exception
	{
		/// <summary>
		/// The line number where the error was encountered.
		/// </summary>
		public readonly int LineNumber;

		/// <summary>
		/// The character position in the line where the error was encountered.
		/// </summary>
		public readonly int LinePosition;

		/// <summary>
		/// A summary of the XML element context where the error was encountered.
		/// </summary>
		public readonly string ElementContext;

		/// <inherit/>
		public override string Message { get { return this._message; } }
		private readonly string _message;

		/// <summary>
		/// Constructor.
		/// </summary>
		public XmlError (NiceXmlReader rdr, string description)
			: base (description + " in line " + rdr.LineNumber.ToString() + ", pos " + rdr.LinePosition)
		{
			this.LineNumber = rdr.LineNumber;
			this.LinePosition = rdr.LinePosition;
			this.ElementContext = rdr.GetElementContext();

			this._message = (description != null) ? description : "indescribable error";

			if (rdr.LineNumber >= 0)
			{
				this._message += " in line " + rdr.LineNumber.ToString();
				if (rdr.LinePosition >= 0)
					this._message += ", pos " + rdr.LinePosition;
			}

			if (!string.IsNullOrEmpty(this.ElementContext))
				this._message += " at " + this.ElementContext;
		}
	}

}
